<!--
 * @Author: Liz.Zheng
 * @Date: 2021-12-07 15:05:42
 * @LastEditTime: 2023-02-16 10:19:56
 * @LastEditors: 郑亚莉 zhengyali@shequ.life
 * @Description: 物业条款
 * @Motto: Write the code. Change the world.
-->

<template>
  <a-card :title="titleShow">
    <template #extra>
      <a-space>
        <a-dropdown
          v-if="canAddNormalClause"
          placement="bottom"
          :trigger="['click']"
        >
          <a-button type="text">
            <template #icon>
              <PlusCircleOutlined />
            </template>
          </a-button>
          <template #overlay>
            <a-menu @click="handleAddClick">
              <a-menu-item key="top"> 向上插入条款 </a-menu-item>
              <a-menu-divider />
              <a-menu-item key="under"> 向下插入条款 </a-menu-item>
            </a-menu>
          </template>
        </a-dropdown>
        <a-button type="text" v-if="index > 0" @click="handleRemove">
          <template #icon>
            <CloseOutlined />
          </template>
        </a-button>
      </a-space>
    </template>
    <!-- 托管计租方式成本合同特殊处理 -->
    <template v-if="isCostContract && isHostedCost">
      <a-form layout="vertical">
        <a-row :gutter="24" :wrap="true">
          <a-col :sm="24" :md="12" :lg="8" :xl="6">
            <a-form-item label="费用类型" v-bind="validateInfos.cost_type">
              <a-select
                v-model:value="modelRef.cost_type"
                placeholder="请选择"
                :disabled="true"
              >
                <a-select-option
                  v-for="item of modelRef.cost_type_list"
                  :value="item.key"
                  :key="item.key"
                >
                  {{ item.name }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :sm="24" :md="12" :lg="8" :xl="6">
            <a-form-item label="分成占比" v-bind="validateInfos.divide_rate">
              <a-input-group compact>
                <a-input-number
                  placeholder="请输入"
                  v-model:value="modelRef.divide_rate"
                  style="width: 80%"
                  :min="0"
                  :precision="2"
                />
                <a-input
                  style="width: 20%"
                  v-model:value="modelRef.divide_rate_suffix"
                  placeholder="%"
                  disabled
                />
              </a-input-group>
            </a-form-item>
          </a-col>
          <a-col :sm="24" :md="12" :lg="8" :xl="6">
            <a-form-item v-bind="validateInfos.cost_compute_rule">
              <template #label>
                <span style="margin-right: 6px;">计算规则</span>
                <a-tooltip>
                  <template #title >
                    <div>计算规则影响部分在成本合同租期外的收款账单是否给业主进行分成</div>
                  </template >
                  <QuestionCircleOutlined />
                </a-tooltip>
              </template>
              <a-select
                v-model:value="modelRef.cost_compute_rule"
                placeholder="请选择"
              >
                <a-select-option
                  v-for="item of optionData.cost_compute_rule"
                  :value="item.key"
                  :key="item.key"
                >
                  {{ item.name }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :sm="24" :md="12" :lg="8" :xl="6">
            <a-form-item v-bind="validateInfos.payment_time">
              <template #label>
                <span style="margin-right: 6px;">付款时间</span>
                <a-tooltip>
                  <template #title >
                    <div>以账单的生成时间计算付款账单应付时间</div>
                  </template >
                  <QuestionCircleOutlined />
                </a-tooltip>
              </template>
              <a-input-group compact>
                <a-select
                  style="width: 30%"
                  v-model:value="modelRef.payment_time_unit1"
                  :disabled="payment_time_unit1_disable"
                  :showArrow="!payment_time_unit1_disable"
                  @select="handlePayTimeDateChange"
                >
                  <a-select-option
                    v-for="item of optionData.payment_time_unit1"
                    :value="item.key"
                    :key="item.key"
                  >
                    {{ item.name }}
                  </a-select-option>
                </a-select>
                <a-input-number
                  placeholder="请输入"
                  v-model:value="modelRef.payment_time"
                  style="width: 30%"
                  :min="0"
                />
                <a-select
                  style="width: 40%"
                  v-model:value="modelRef.payment_time_unit2"
                >
                  <a-select-option
                    v-for="item of optionData.payment_time_unit2"
                    :value="item.key"
                    :key="item.key"
                  >
                    {{ item.name }}
                  </a-select-option>
                </a-select>
              </a-input-group>
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </template>
    <template v-else>
      <a-form layout="vertical">
        <a-row :gutter="24" :wrap="true">
          <a-col
            :sm="24"
            :md="12"
            :lg="8"
            :xl="6"
            v-if="type == 'lease' || (type == 'property' && isCostContract)"
          >
            <a-form-item label="计租方式" v-bind="validateInfos.compute_lease">
              <!-- 物业条款特殊处理  compute_lease_list-->
              <template
                v-if="isCostContract && type == 'property' && !isHostedCost"
              >
                <a-select
                  v-model:value="modelRef.compute_lease"
                  placeholder="请选择"
                  @select="handleComputeLeaseChange"
                  :disabled="true"
                >
                  <a-select-option
                    v-for="item of modelRef.compute_lease_list"
                    :value="item.key"
                    :key="item.key"
                  >
                    {{ item.name }}
                  </a-select-option>
                </a-select>
              </template>
              <template v-else>
                <!-- 成本合同置灰禁用 -->
                <a-select
                  v-model:value="modelRef.compute_lease"
                  placeholder="请选择"
                  @select="handleComputeLeaseChange"
                  :disabled="isCostContract"
                >
                  <a-select-option
                    v-for="item of optionData.compute_lease_unit"
                    :value="item.key"
                    :key="item.key"
                  >
                    {{ item.name }}
                  </a-select-option>
                </a-select>
              </template>
            </a-form-item>
          </a-col>
          <a-col :sm="24" :md="12" :lg="8" :xl="6">
            <a-form-item label="起始时间" v-bind="validateInfos.charge_time">
              <a-range-picker
                v-model:value="modelRef.charge_time"
                :valueFormat="dateFormatStr"
                @change="handleChargeTimeChange"
                :disabled-date="disabledDate"
              />
            </a-form-item>
          </a-col>
          <a-col
            :sm="24"
            :md="12"
            :lg="8"
            :xl="6"
            v-if="modelRef.compute_lease != 'unit2'"
          >
            <a-form-item
              label="合同单价"
              v-bind="validateInfos.contract_unit_price"
            >
              <a-input-group compact>
                <a-input-number
                  placeholder="请输入"
                  v-model:value="modelRef.contract_unit_price"
                  style="width: 60%"
                  :min="0"
                  :precision="pricePoint"
                />
                <a-select
                  style="width: 40%"
                  v-model:value="modelRef.contract_price_unit"
                  @select="handleContractPriceChange"
                >
                  <a-select-option
                    v-for="item of optionData.contract_price_unit"
                    :value="item.key"
                    :key="item.key"
                  >
                    {{ item.name }}
                  </a-select-option>
                </a-select>
              </a-input-group>
            </a-form-item>
          </a-col>
          <a-col :sm="24" :md="12" :lg="8" :xl="6">
            <a-form-item v-bind="validateInfos.payment_time">
              <template #label>
                <span>付款时间</span>
                <a-tooltip v-if="specifyDatePay">
                  <template #title>
                    账单应收日期固定为当月的指定日期收款
                  </template>
                  <QuestionCircleOutlined
                    style="color: #999; margin-left: 5px"
                  />
                </a-tooltip>
              </template>
              <a-input-group compact style="display: flex; align-items: center">
                <a-select
                  style="width: 40%"
                  v-model:value="modelRef.payment_time_unit1"
                  @select="handlePayTimeDateChange"
                >
                  <a-select-option
                    v-for="item of optionData.payment_time_unit1"
                    :value="item.key"
                    :key="item.key"
                  >
                    {{ item.name }}
                  </a-select-option>
                </a-select>
                <a-input-number
                  placeholder="请输入"
                  v-model:value="modelRef.payment_time"
                  style="flex: 1"
                  :min="0"
                />
                <span class="num-input-suffix" v-if="specifyDatePay">日</span>
                <a-select
                  style="width: 30%"
                  v-model:value="modelRef.payment_time_unit2"
                  v-else
                >
                  <a-select-option
                    v-for="item of optionData.payment_time_unit2"
                    :value="item.key"
                    :key="item.key"
                  >
                    {{ item.name }}
                  </a-select-option>
                </a-select>
              </a-input-group>
            </a-form-item>
          </a-col>
          <a-col :sm="24" :md="12" :lg="8" :xl="6" v-if="specifyDatePay">
            <a-form-item
              label="指定日期"
              v-bind="validateInfos.specify_date_unit"
            >
              <a-select
                v-model:value="modelRef.specify_date_unit"
                placeholder="请选择"
              >
                <a-select-option
                  v-for="item of optionData.specify_date_unit"
                  :value="item.key"
                  :key="item.key"
                >
                  {{ item.name }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :sm="24" :md="12" :lg="8" :xl="6">
            <a-form-item v-bind="validateInfos.charge_type">
              <template #label>
                <span style="margin-right: 6px;">计费类型</span>
                <a-tooltip>
                  <template #title >
                    <div>1、天单价=实际输入天单价 或者 月单价*12/年天数 或者 月单价/自然月天数</div>
                    <div>2、月单价=实际输入月单价 或者 天单价*年天数/12</div>
                    <div>3、总价=（月单价*月数*面积）+（天单价*实际天数*面积）</div>
                    <div>4、以月计租时，整月按公式3第一项计算，余下的天数按照公式3的第二项计算</div>
                  </template >
                  <QuestionCircleOutlined />
                </a-tooltip>
              </template>
              <a-select
                v-model:value="modelRef.charge_type"
                placeholder="请选择"
              >
                <a-select-option
                  v-for="item of optionData.charge_type_unit"
                  :value="item.key"
                  :key="item.key"
                >
                  {{ item.name }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :sm="24" :md="12" :lg="8" :xl="6" v-if="showUnitPriceRule">
            <a-form-item v-bind="validateInfos.convert_day_price">
              <template #label>
                <span style="margin-right: 6px;">天单价换算规则</span>
                <a-tooltip>
                  <template #title >
                    <div>按年换算：天单价=月单价*12/年天数</div>
                    <div>按自然月换算：天单价=月单价/自然月的天数</div>
                  </template >
                  <QuestionCircleOutlined />
                </a-tooltip>
              </template>
              <a-select
                v-model:value="modelRef.convert_day_price"
                placeholder="请选择"
              >
                <a-select-option
                  v-for="item of optionData.convert_day_price"
                  :value="item.key"
                  :key="item.key"
                >
                  {{ item.name }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :sm="24" :md="12" :lg="8" :xl="6">
            <a-form-item v-bind="validateInfos.year_days">
              <template #label>
                <span style="margin-right: 6px;">年天数</span>
                <a-tooltip>
                  <template #title >
                    <div>按年换算：天单价=月单价*12/年天数</div>
                    <div>按自然月换算：天单价=月单价/自然月的天数</div>
                  </template >
                  <QuestionCircleOutlined />
                </a-tooltip>
              </template>
              <a-input-group compact>
                <a-input-number
                  placeholder="请输入"
                  v-model:value="modelRef.year_days"
                  style="width: 80%"
                  :min="0"
                />
                <span class="num-input-suffix">天</span>
              </a-input-group>
            </a-form-item>
          </a-col>
          <a-col :sm="24" :md="12" :lg="8" :xl="6">
            <a-form-item
              label="付款周期（几月一付）"
              v-bind="validateInfos.payCycle"
            >
              <a-input-group compact style="display: flex; align-items: center">
                <a-input-number
                  placeholder="请输入"
                  v-model:value="modelRef.payCycle"
                  style="flex: 1"
                  :precision="0"
                  :min="0"
                />
                <span class="num-input-suffix">月</span>
              </a-input-group>
            </a-form-item>
          </a-col>
          <a-col :sm="24" :md="12" :lg="8" :xl="6">
            <a-form-item v-bind="validateInfos.lease_divide">
              <template #label>
                <span style="margin-right: 6px;">租期划分方式</span>
                <a-tooltip>
                  <template #title >
                    <div>按起始日划分</div>
                    <div>次月按自然月划分(仅一月一付有效)</div>
                    <div>按自然月划分(首月非整自然月划入第一期)</div>
                    <div>按自然月划分(首月非整自然月算一个月)</div>
                  </template >
                  <QuestionCircleOutlined />
                </a-tooltip>
              </template>
              <a-select
                v-model:value="modelRef.lease_divide"
                placeholder="请选择"
              >
                <a-select-option
                  v-for="item of optionData.lease_divide_unit"
                  :value="item.key"
                  :key="item.key"
                >
                  {{ item.name }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :sm="24" :md="12" :lg="8" :xl="6" v-if="showComputedRatio">
            <a-form-item
              label="分成方式"
              v-bind="validateInfos.divide_mode_unit"
            >
              <a-select
                v-model:value="modelRef.divide_mode_unit"
                placeholder="请选择"
                @select="handleDivideModeChange"
              >
                <a-select-option
                  v-for="item of optionData.divide_mode_unit"
                  :value="item.key"
                  :key="item.key"
                >
                  {{ item.name }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :sm="24" :md="12" :lg="8" :xl="6" v-if="showComputedRatio">
            <a-form-item
              label="区间闭合方式"
              v-bind="validateInfos.section_mode_unit"
            >
              <a-select
                v-model:value="modelRef.section_mode_unit"
                placeholder="请选择"
                @select="handleSectionModeChange"
              >
                <a-select-option
                  v-for="item of optionData.section_mode_unit"
                  :value="item.key"
                  :key="item.key"
                >
                  {{ item.name }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>
        <template v-if="showComputedRatio">
          <div class="text-title">
            <span class="required">*</span>
            {{ divideModeType == 1 ? "固定分成" : "阶梯分成" }}
          </div>
          <template v-if="divideInterval.list.length">
            <a-row
              :gutter="24"
              v-for="(item, index) of divideInterval.list"
              :key="item.key"
            >
              <a-col :sm="24" :md="12" :lg="8" :xl="6">
                <a-form-item :label="index == 0 ? divideInterval.label1 : ''">
                  <a-input
                    placeholder="请输入"
                    v-model:value="item.minPrice"
                    suffix="元"
                    :disabled="item.minPriceDisabled == true"
                  />
                </a-form-item>
              </a-col>
              <a-col :sm="24" :md="12" :lg="8" :xl="6">
                <a-form-item :label="index == 0 ? divideInterval.label2 : ''">
                  <a-input
                    placeholder="请输入"
                    v-model:value="item.maxPrice"
                    suffix="元"
                    :disabled="item.maxPriceDisabled == true"
                    @change="(e) => handleMaxPriceInput(e.target.value, index)"
                    @blur="handleMaxPriceInputBlur(item, index)"
                  />
                </a-form-item>
              </a-col>
              <a-col :sm="24" :md="12" :lg="8" :xl="6">
                <a-form-item :label="index == 0 ? divideInterval.label3 : ''">
                  <a-input
                    placeholder="请输入"
                    v-model:value="item.ratio"
                    suffix="%"
                  />
                </a-form-item>
              </a-col>
              <a-col
                :sm="24"
                :md="12"
                :lg="8"
                :xl="6"
                v-if="index > 0 && index < divideInterval.list.length - 1"
              >
                <a-button type="text" @click="handleIntervalRemove(index)">
                  <template #icon>
                    <CloseOutlined />
                  </template>
                </a-button>
              </a-col>
            </a-row>
          </template>
          <a-row v-if="divideModeType == 2">
            <a-button
              type="primary"
              ghost
              size="small"
              @click="addDivideInterval"
            >
              <template #icon>
                <PlusOutlined />
              </template>
              区间
            </a-button>
          </a-row>
        </template>
      </a-form>
    </template>
  </a-card>
</template>

<script>
import {
  defineComponent,
  reactive,
  watch,
  ref,
  computed,
  onMounted,
  nextTick,
  toRaw,
} from "vue";
import { TextTip } from "bl-common-vue3";
import {
  CloseOutlined,
  PlusOutlined,
  QuestionCircleOutlined,
  PlusCircleOutlined,
} from "@ant-design/icons-vue";
import { Form, message } from "ant-design-vue";
import store from "../../../../store";
import utils from "../../../../common/utils/utils";
import moment from "moment";
import { useRoute } from "vue-router";
const useForm = Form.useForm;
import _ from "lodash";

export default defineComponent({
  name: "NormalClause",
  props: {
    title: {
      type: String,
      default: "",
    },
    index: {
      type: Number,
      default: 0,
    },
    // 条款类型 lease租赁条款 property物业条款
    type: {
      type: String,
      default: "lease",
    },
    // 触发验证
    trigger: {
      type: Number,
      default: 0,
    },
    paneFrom: {
      type: String,
      default: "default",
    },
    content: {
      type: Object,
      default: () => {
        return {};
      },
    },
    isHostedCost: {
      type: Boolean,
      default: false,
    },
    canAddNormalClause: {
      type: Boolean,
      default: false,
    },
    clauseContent: {
      type: Object,
      default: () => {
        return {};
      },
    }
  },
  components: {
    CloseOutlined,
    PlusOutlined,
    TextTip,
    QuestionCircleOutlined,
    PlusCircleOutlined,
  },
  setup(props, context) {
    const dateFormatStr = "YYYY-MM-DD";
    const disabledDate = (current) => {
      const { startDate, endDate } = contractDateRange.value;
      return (
        current < moment(startDate).startOf("day") ||
        current > moment(endDate).endOf("days")
      );
    };

    const state = reactive({
      specialCostType: [{ key: "cost_36", name: "成本租金" }],
      specialComputeLease: [{ key: "unit1", name: "固定物业费" }],
      defaultCostType: [],
      defaultComputeLease: [],
    });

    const titleShow = computed(() => {
      let title = props.title || props.content.title;
      if (props.index > 0) {
        title = title + props.index;
      }
      return title;
    });

    const $route = useRoute();
    // 是否成本合同
    const isCostContract = computed(
      () => $route.query.contractType == "costContract"
    );

    /**
     * @description: 选择监听
     */
    // 监听计租方式选择
    const showComputedRatio = ref(false);
    const handleComputeLeaseChange = (value) => {
      showComputedRatio.value = value != "unit1";
      setModelAndRule({
        type: showComputedRatio.value ? "add" : "remove",
        key: "divide_mode_unit",
        valueType: {
          list: optionData.value.divide_mode_unit,
        },
      });
      if (showComputedRatio.value && props.content.divide_mode) {
        handleDivideModeChange(modelRef.divide_mode_unit);
      }
      setModelAndRule({
        type: showComputedRatio.value ? "add" : "remove",
        key: "section_mode_unit",
        valueType: {
          list: optionData.value.section_mode_unit,
        },
      });
      setModelAndRule({
        type: value == "unit2" ? "remove" : "add",
        key: "contract_unit_price",
        rule: { required: true },
      });
      setModelAndRule({
        type: value == "unit2" ? "remove" : "add",
        key: "contract_price_unit",
        valueType: {
          list: optionData.value.contract_price_unit,
        },
      });
      context.emit("change", { key: props.paneFrom, compute_lease: value });
    };
    // 监听分成方式选择
    const divideModeType = ref(1); // 1固定比例 2阶梯比例
    const handleDivideModeChange = (value) => {
      divideModeType.value = value == "unit1" ? 1 : 2;
      const divide_mode = props.content.divide_mode;
      if (divide_mode && divide_mode.length) {
        divideInterval.value.list = divide_mode.map((item, index) => {
          if (index == 0) {
            item.minPriceDisabled = true;
          }
          if (index == divide_mode.length - 1) {
            item.maxPriceDisabled = true;
          }
          if (item.maxPrice == -1) {
            item.maxPrice = "∞";
          }
          return item;
        });
      } else {
        divideInterval.value.list =
          divideModeType.value == 1
            ? JSON.parse(JSON.stringify(fixedDIList))
            : JSON.parse(JSON.stringify(ladderDIList));
      }
    };
    // 监听区间开闭方式选择
    const handleSectionModeChange = (value) => {
      divideInterval.value.label1 = diLabel1 + (value == "unit1" ? "" : "等于"); // 左开右闭
      divideInterval.value.label2 = diLabel2 + (value == "unit1" ? "等于" : ""); // 左闭右开
    };
    // 监听价格区间输入
    const handleMaxPriceInput = (value, index) => {
      if (divideModeType.value == 2 && divideInterval.value.list[index + 1]) {
        divideInterval.value.list[index + 1].minPrice = value;
      }
    };
    const handleMaxPriceInputBlur = (current, index) => {
      console.log("----------------handleMaxPriceInputBlur", current);
      if (
        current.maxPrice &&
        Number(current.maxPrice) <= Number(current.minPrice)
      ) {
        current.maxPrice = Number(current.minPrice) + 1;
        message.warning("区间最大值应当大于区间最小值");
        handleMaxPriceInput(current.maxPrice, index);
      }
    };
    // 监听合同单位选择
    const showUnitPriceRule = ref(false);
    const handleContractPriceChange = (value) => {
      showUnitPriceRule.value = !["unit_1", "unit_4"].includes(value);
      setModelAndRule({
        type: showUnitPriceRule.value ? "add" : "remove",
        key: "convert_day_price",
        valueType: optionData.value.convert_day_price,
        rule: { required: true },
      });
    };
    // 监听付款时间付款限制选择
    const specifyDatePay = ref(false);
    const handlePayTimeDateChange = (value) => {
      specifyDatePay.value = value == "unit_3" || value == "unit_4";
      setModelAndRule({
        type: specifyDatePay.value ? "add" : "remove",
        key: "specify_date_unit",
        valueType: optionData.value.specify_date_unit,
        rule: { required: true },
      });
    };
    // 监听起始时间改变
    const handleChargeTimeChange = (date, dateString) => {
      store.dispatch("SetContractDateRange", { lastEndDate: dateString[1] });
    };

    const pricePoint = computed(
      () => store.getters.addFormData.basicInfo.unit_price_point || 2
    );

    /**
     * @description:表单
     */
    const modelRef = reactive({
      compute_lease: undefined, // 计租方式
      charge_time: [], // 起始时间
      contract_unit_price: "", //合同单价
      contract_price_unit: undefined, //合同单价单位
      payment_time_unit1: undefined, // 付款时间单位1
      payment_time: "", // 付款时间
      payment_time_unit2: undefined, // 付款时间单位2
      charge_type: undefined, // 计费类型
      year_days: 365, // 年天数
      payCycle: "", // 付款周期
      lease_divide: undefined, // 租期划分方式
      // divide_mode_unit: undefined, // 分成方式
      // section_mode_unit: undefined, // 区间闭合方式

      cost_type: undefined, //费用类型
      divide_rate: "", //分成占比
      cost_compute_rule: undefined, //计费规则
      cost_type_list: [],
      compute_lease_list: [],
      showCostType: true,
    });
    const numberRule = [
      {
        required: true,
        validator: (rules, value) => utils.pNumberValidator(rules, value),
        trigger: "change",
      },
    ];

    const costTypeList = computed(() => {
      return isCostContract.value && props.isHostedCost ? state.specialCostType : state.defaultCostType;
    });

    const computeLeaseList = computed(() => {
      return isCostContract.value && props.type == 'property' && !props.isHostedCost ? state.specialComputeLease : state.defaultComputeLease;
    });

    // 自然数
    const numberRule2 = [
      {
        required: true,
        validator: (rules, value) => utils.nNumberValidator(rules, value),
        trigger: "change",
      },
    ];
    const rulesRef = reactive({
      compute_lease: [{ required: true, message: "必填" }],
      charge_time: [{ required: true, message: "必填" }],
      contract_unit_price: [{ required: true, message: "必填" }],
      payment_time: numberRule2,
      charge_type: [{ required: true, message: "必填" }],
      year_days: numberRule,
      payCycle: numberRule,
      lease_divide: [{ required: true, message: "必填" }],
    });

    const payment_time_unit1_disable = ref(false);
    const checkPaymentTime = (isCostContract) => {
      if (isCostContract && props.isHostedCost) {
        // 成本合同-托管计租-付款时间 : 只有延后，没有提前
        optionData.value.payment_time_unit1 = [{ key: "unit_2", name: "延后" }];
        modelRef.payment_time_unit1 = "unit_2";
        payment_time_unit1_disable.value = true;
      } else {
        optionData.value.payment_time_unit1 = [
          { key: "unit_1", name: "提前" },
          { key: "unit_2", name: "延后" },
          { key: "unit_3", name: "指定日期" },
        ];
        modelRef.payment_time_unit1 = "unit_1";
        payment_time_unit1_disable.value = false;
      }
    };

    watch(
      () => $route.query.contractType,
      (val) => {
        //是成本合同
        if (val && val == "costContract") {
          // 是托管计租方式
          if (props.isHostedCost) {
            checkPaymentTime(isCostContract);
          } else {
            checkPaymentTime();
          }
        } else {
          checkPaymentTime();
        }
      }
    );

    watch(
      () => props.isHostedCost,
      (val) => {
        if (isCostContract.value) {
          modelRef.payment_time = "";
          if (val === true) {
            // 托管计租

            // 清除普通合同必填项
            delete rulesRef.charge_time;
            delete rulesRef.contract_unit_price;
            delete rulesRef.charge_type;
            delete rulesRef.year_days;
            delete rulesRef.payCycle;
            delete rulesRef.lease_divide;

            // 托管计租必填
            rulesRef.divide_rate = numberRule;
            rulesRef.cost_compute_rule = [{ required: true, message: "必填" }];
          } else {
            setModelAndRule("add", "charge_time");
            rulesRef.charge_time = [{ required: true, message: "必填" }];
            rulesRef.contract_unit_price = [
              { required: true, message: "必填" },
            ];
            rulesRef.payment_time = numberRule;
            rulesRef.charge_type = [{ required: true, message: "必填" }];
            rulesRef.year_days = numberRule;
            rulesRef.payCycle = numberRule;
            rulesRef.lease_divide = [{ required: false, message: "必填" }];

            delete rulesRef.divide_rate;
            delete rulesRef.cost_compute_rule;
          }
        }

        if (val === true) {
          if (isCostContract.value) {
            checkPaymentTime(isCostContract);
          } else {
            checkPaymentTime();
          }
        } else {
          checkPaymentTime();
        }
      }
    );

    const setModelAndRule = ({ type = "add", key, valueType, value, rule }) => {
      const { content } = props;
      if (type == "add" && !modelRef[key]) {
        modelRef[key] = undefined;
        if (content[key]) {
          modelRef[key] = content[key];
        } else if (valueType) {
          setDefaultModel(valueType.list, key);
        } else {
          modelRef[key] = value;
        }
        if (rule && rule.required) {
          rulesRef[key] = [{ required: true, message: "必填" }];
        }
      }
      if (type == "remove") {
        delete modelRef[key];
        delete rulesRef[key];
      }
      // console.log("setModelAndRule modelRef", toRaw(modelRef));
      // console.log("setModelAndRule rulesRef", toRaw(rulesRef));
    };
    const { resetFields, validate, validateInfos } = useForm(
      modelRef,
      rulesRef
    );
    const validateForm = () => {
      // console.log("-------------validateForm", toRaw(rulesRef));
      validate()
        .then(() => {
          let divide_mode = [];
          if (showComputedRatio.value) {
            for (let item of divideInterval.value.list) {
              if (
                (!item.minPrice && item.minPrice != 0) ||
                item.maxPrice == "" ||
                item.ratio == ""
              ) {
                context.emit("fail", {
                  type: "normal",
                  msg: "请完善条款分成信息~",
                });
                return;
              }
              divide_mode.push({
                minPrice: Number(item.minPrice),
                maxPrice: item.maxPriceDisabled ? -1 : Number(item.maxPrice),
                ratio: Number(item.ratio),
              });
            }
          }
          let params = JSON.parse(JSON.stringify(modelRef));
          params.charge_begintime = params.charge_time[0];
          params.charge_endtime = params.charge_time[1];
          delete params.charge_time;
          params.compute_lease = params.compute_lease || "unit1";
          if (divide_mode.length) {
            params.divide_mode = divide_mode;
          }
          // 指定日期时，不传（自然日/工作日单位）
          if (specifyDatePay.value) {
            delete params.payment_time_unit2;
          }
          context.emit("success", {
            type: "normal",
            content: params,
          });
        })
        .catch(() => {
          context.emit("fail", {
            type: "normal",
          });
        });
    };

    /**
     * @description: 分成方式
     */
    const divideInterval = ref({
      label1: diLabel1,
      label2: diLabel2 + "等于",
      label3: diLabel3,
      list: JSON.parse(JSON.stringify(fixedDIList)),
    });
    // 添加分成区间
    let addCount = 1;
    const addDivideInterval = () => {
      if (divideModeType.value == 1) {
        divideInterval.value.list.push({
          key: "divide_interval_" + addCount,
          minPrice: "",
          maxPrice: "",
          ratio: "",
        });
      } else {
        const spliceIndex = divideInterval.value.list.length - 1; // 插入的index节点
        divideInterval.value.list.splice(spliceIndex, 0, {
          key: "divide_interval_" + addCount,
          minPrice: divideInterval.value.list[spliceIndex - 1].maxPrice,
          maxPrice: "",
          ratio: "",
        });
      }
    };
    // 删除区间
    const handleIntervalRemove = (index) => {
      divideInterval.value.list.splice(index, 1);
    };

    const setDetail = () => {
      const { content, paneFrom } = props;
      if (content) {
        console.log("setDetail", content);
        if (content.compute_lease) {
          modelRef.compute_lease = content.compute_lease || "unit1";
          handleComputeLeaseChange(modelRef.compute_lease);
        }
        if (content.charge_begintime) {
          // 比较合同租赁时间和条款时间，条款时间超过租赁时间的需要改变
          // 如果条款开始在租赁时间之前，则开始时间变为合同租赁开始时间
          // 如果条款结束在租赁时间之后，则结束时间变为合同租赁结束时间
          let tmp_begin = content.charge_begintime;
          let tmp_end = content.charge_endtime;
          const { startDate, endDate } = contractDateRange.value;
          if (startDate && endDate) {
            // 如果条款开始在租赁时间之前，则开始时间变为合同租赁开始时间
            if (moment(tmp_begin).isBefore(startDate)) {
              tmp_begin = startDate;
              // 改变条款时间，需要清空租金明细，重新手动生成
              store.dispatch("SetClearRentDetail", true);
            }
            // 如果条款结束在租赁时间之后，则结束时间变为合同租赁结束时间
            if (moment(tmp_end).isAfter(endDate)) {
              tmp_end = endDate;
              store.dispatch("SetClearRentDetail", true);
            }
          }
          console.log("tmp_begin, tmp_end", tmp_begin, tmp_end);
          modelRef.charge_time = [tmp_begin, tmp_end];
        }

        modelRef.payment_time = content.payment_time ?? '';
        modelRef.payment_time_unit1 = content.payment_time_unit1;
        modelRef.payment_time_unit2 = content.payment_time_unit2;
        modelRef.payment_time_unit1 &&
          handlePayTimeDateChange(modelRef.payment_time_unit1);
        modelRef.contract_unit_price = content.contract_unit_price;
        modelRef.contract_price_unit = content.contract_price_unit;
        modelRef.contract_price_unit &&
          handleContractPriceChange(modelRef.contract_price_unit);
        modelRef.payCycle = content.payCycle || content.payCycle == 0 ? content.payCycle : '';
        modelRef.charge_type = content.charge_type;
        modelRef.lease_divide = content.lease_divide;

        nextTick(() => {
          store.dispatch("SetClauseTabChange", {
            key: paneFrom,
            changed: false,
          });
          watch(modelRef, (value) => {
            const changed =
              store.getters.clauseContentList[props.paneFrom].changed;
            if (!changed) {
              store.dispatch("SetClauseTabChange", {
                key: props.paneFrom,
                changed: true,
              });
            }
          });
        });
      }
    };

    const optionData = ref({});
    const originPaymentUnit1 = ref([]);

    const paymentByRooms = computed(() => {
      return store.getters.orgInfo.paymentByRooms;
    });

    const init = () => {
      if (props?.clauseContent?.cost_type && props?.clauseContent?.cost_type_name) {
        let costList = [{ key: props.clauseContent.cost_type, name: props.clauseContent.cost_type_name }];
        state.defaultCostType = costList;
        state.defaultComputeLease = costList;
      }
      store.dispatch("ContractInit").then((res) => {
        console.log("----------", res);
        optionData.value = res;

        originPaymentUnit1.value = res.payment_time_unit1;
        setDefaultModel(res.compute_lease_unit, "compute_lease");
        if (paymentByRooms.value) {
          let list = ["unit_3", "unit_4", "unit_5"];
          let contract_price_unit = [];
          res.contract_price_unit.forEach((item) => {
            if (list.includes(item.key)) {
              contract_price_unit.push(item);
            }
          });
          optionData.value.contract_price_unit = [];
          optionData.value.contract_price_unit.push(...contract_price_unit);
          setDefaultModel(
            optionData.value.contract_price_unit,
            "contract_price_unit"
          );
        } else {
          setDefaultModel(res.contract_price_unit, "contract_price_unit");
        }

        setDefaultModel(res.payment_time_unit1, "payment_time_unit1");
        setDefaultModel(res.payment_time_unit2, "payment_time_unit2");
        setDefaultModel(res.charge_type_unit, "charge_type");
        setDefaultModel(res.lease_divide_unit, "lease_divide");
        setChargeDate();
        // setDefaultModel(res.divide_mode_unit, "divide_mode_unit");
        // setDefaultModel(res.section_mode_unit, "section_mode_unit");
        // setDetail();

        if (isCostContract.value) {
          if (props.type == "property") {
            //物业条款-计租方式
            modelRef.compute_lease = "unit1";
            // 物业条款-费用类型
            state.specialCostType = [{ key: "cost_37", name: "成本物业费" }];
          }
          modelRef.cost_type = modelRef.cost_type_list[0].key;
          // 物业条款-计费规则
          modelRef.cost_compute_rule_list = optionData.value.cost_compute_rule;
          modelRef.cost_compute_rule =
            optionData.value.cost_compute_rule &&
            optionData.value.cost_compute_rule.length
              ? optionData.value.cost_compute_rule[0].key
              : undefined;
        }

        initDetail();
      });
    };
    const setDefaultModel = (list, key, id = "key") => {
      modelRef[key] =
        modelRef[key] || (list && list.length) ? list[0][id] : undefined;
      if (key == "compute_lease") {
        context.emit("change", {
          key: props.paneFrom,
          compute_lease: modelRef.compute_lease,
        });
      }
      if (key == "section_mode_unit") {
        handleSectionModeChange(modelRef.section_mode_unit);
      }
    };

    let setDetailFlag = true;
    const initDetail = () => {
      if (
        props.content &&
        (props.content.compute_lease || store.getters.tplContent.id)
      ) {
        if (setDetailFlag) {
          setDetail();
          setDetailFlag = false;
        } else {
          setChargeDate();
        }
      } else {
        setChargeDate();
      }
    };
    watch(
      () => store.getters.currentStep,
      (newVal, oldVal) => {
        if (newVal == 1 && oldVal == 0) {
          // 第一次从第一步跳到第二步时，如果有详情数据，则setDetail
          console.log("props.content", props.content);
          initDetail();
        }
      }
    );

    const contractDateRange = computed(() => store.getters.contractDateRange);
    const setChargeDate = () => {
      const { startDate, endDate, lastEndDate } = contractDateRange.value;
      if (startDate && endDate) {
        if (modelRef.charge_time[0] && modelRef.charge_time[1]) {
          let tmp_begin = modelRef.charge_time[0];
          let tmp_end = modelRef.charge_time[1];

          // 如果条款开始在租赁时间之前，则开始时间变为合同租赁开始时间
          if (moment(tmp_begin).isBefore(startDate)) {
            tmp_begin = startDate;
            // 改变条款时间，需要清空租金明细，重新手动生成
            store.dispatch("SetClearRentDetail", true);
          }
          // 如果条款结束在租赁时间之后，则结束时间变为合同租赁结束时间
          if (moment(tmp_end).isAfter(endDate)) {
            tmp_end = endDate;
            store.dispatch("SetClearRentDetail", true);
          }

          modelRef.charge_time[0] = tmp_begin;
          modelRef.charge_time[1] = tmp_end;
        } else {
          modelRef.charge_time[0] = startDate;
          modelRef.charge_time[1] = endDate;
        }
      }
    };

    init();

    watch(
      () => props.trigger,
      (trigger) => {
        if (trigger) {
          validateForm();
        }
      }
    );

    watch(
      () => costTypeList.value,
      (val) => {
        modelRef.cost_type_list = _.cloneDeep(val);
      },
      { deep: true, immediate: true }
    );

    watch(
      () => computeLeaseList.value,
      (val) => {
        modelRef.compute_lease_list = _.cloneDeep(val);
      },
      { deep: true, immediate: true }
    );


    // 删除卡片
    const handleRemove = () => {
      context.emit("remove", { index: props.index, type: "normal" });
    };

    const handleAddClick = (e) => {
      const { key } = e;
      context.emit("add", { index: props.index, type: "normal", way: key });
    };

    watch(
      () => modelRef,
      (val) => {
        context.emit("dataChange", {
          type: "normal",
          content: _.cloneDeep(modelRef),
        });
      }, {deep: true}
    );

    return {
      titleShow,
      pricePoint,
      modelRef,
      validateInfos,
      optionData,
      showComputedRatio,
      divideInterval,
      divideModeType,
      showUnitPriceRule,
      specifyDatePay,
      dateFormatStr,
      disabledDate,
      handleRemove,
      addDivideInterval,
      handleIntervalRemove,
      handleComputeLeaseChange,
      handleDivideModeChange,
      handleSectionModeChange,
      handleMaxPriceInput,
      handleMaxPriceInputBlur,
      handleContractPriceChange,
      handlePayTimeDateChange,
      handleChargeTimeChange,
      isCostContract,
      payment_time_unit1_disable,
      paymentByRooms,
      handleAddClick,
    };
  },
});

let diLabel1 = "营业额大于";
let diLabel2 = "营业额小于";
let diLabel3 = "分成比例";
const fixedDIList = [
  {
    key: "divide_interval_default",
    minPrice: 0,
    minPriceDisabled: true,
    maxPrice: "∞",
    maxPriceDisabled: true,
    ratio: "",
  },
];
const ladderDIList = [
  {
    key: "divide_interval_default1",
    minPrice: 0,
    minPriceDisabled: true,
    maxPrice: "",
    ratio: "",
  },
  {
    key: "divide_interval_default2",
    minPrice: "",
    maxPrice: "∞",
    maxPriceDisabled: true,
    ratio: "",
  },
];
</script>
